package main

import "fmt"

//* Definition for singly-linked list.
type ListNode struct {
	Val  int
	Next *ListNode
}

func mergeKLists(lists []*ListNode) *ListNode {
	// result := ListNode{}
	if len(lists) <= 1 {
		return lists[0]
	}
	result := merge(lists[0], lists[1])
	for i, a := range lists {
		if i <= 1 {
			continue
		}
		result = merge(a, result)
		// result = *b
	}
	return result
}

func merge(a *ListNode, b *ListNode) *ListNode {
	result := ListNode{}

	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	//var result *ListNode
	l1 := a
	l2 := b
	flag := &result
loop:
	for {
		if l1 == nil {
			for {
				if l2 == nil {
					break loop
				}
				newFlag := ListNode{
					Val:  l2.Val,
					Next: nil,
				}
				flag.Next = &newFlag
				flag = flag.Next
				l2 = l2.Next
				// flag.va
			}
		}
		if l2 == nil {
			for {
				if l1 == nil {
					break loop
				}
				newFlag := ListNode{
					Val:  l1.Val,
					Next: nil,
				}
				flag.Next = &newFlag
				flag = flag.Next
				l1 = l1.Next
			}
		}
		if l1.Val > l2.Val {
			newFlag := ListNode{
				Val:  l2.Val,
				Next: nil,
			}
			flag.Next = &newFlag
			flag = flag.Next
			l2 = l2.Next
			// l2 = l2.Next
		} else {
			newFlag := ListNode{
				Val:  l1.Val,
				Next: nil,
			}
			flag.Next = &newFlag
			flag = flag.Next
			l1 = l1.Next
			// l1 = l1.Next
		}
	}
	return result.Next
}

func main() {
	var a *ListNode
	fmt.Println(a)
	b := ListNode{}
	fmt.Println(b)
}
